<template>
  <div class="login" :style="style">
    <theme style="position: fixed; top: 10px; right: 20px" />
    <form class="form_container">
      <div class="logo_container">
        <img :src="logo" alt="" />
      </div>
      <div class="title_container">
        <p class="title">登录 BIU-NET {{ title }}</p>
        <span class="subtitle">登录您的BIU-NET管理员账号，来配置你的服务</span>
      </div>
      <input name="username" style="display: none" aria-hidden="true" autocomplete="username" />
      <div class="input_container">
        <unlock class="icon" theme="filled" size="20" :strokeWidth="3" />
        <input
          autocomplete="new-password"
          placeholder="请输入密码"
          type="password"
          class="input_field"
          v-model="loginRequest.password"
        />
      </div>
      <div class="input_container">
        <Code class="icon" theme="filled" :size="20" :strokeWidth="3" />
        <input
          placeholder="请输入验证码"
          type="text"
          class="input_field"
          v-model="loginRequest.captchaCode"
        />
        <img :src="captcha?.imageBase64" alt="" @click="generateCaptcha" />
      </div>
      <button @click="login" title="Sign In" type="button" class="sign-in_btn">
        <span>登录</span>
      </button>
      <p class="note">Power by @BIU-NET</p>
    </form>
  </div>
</template>

<script setup lang="ts">
import logo from "@/assets/img/logo.png"
import Theme from "@/components/theme/Index.vue"
import { Code, Unlock } from "@icon-park/vue-next"
import { useThemeVar } from "@/utils/theme-util"
import { useEnvType } from "@/utils/env-util"
import { onMounted, ref } from "vue"
import type { CaptchaImage, LoginRequest } from "@/api/passport-api"
import { doGenerateCaptcha, doLogin } from "@/api/passport-api"
import { useLocalStorage } from "@vueuse/core"
import { useRouter } from "vue-router"
import { ACCESS_TOKEN_NAME } from "@/utils/constants"

const title = useEnvType("客户端", "服务中心")

const style = useThemeVar(
  {
    "--login-form-container-background-color": "rgba(0, 0, 0, 0.25)",
    "--login-form-input-border-color": "rgba(255, 255, 255, 0.5)"
  },
  {
    "--login-form-container-background-color": "rgba(255, 255, 255, 0.25)",
    "--login-form-input-border-color": "rgba(0, 0, 0, 0.5)"
  }
)

onMounted(() => {
  generateCaptcha()
})

const captcha = ref<CaptchaImage>()

function generateCaptcha() {
  doGenerateCaptcha().then((res) => {
    captcha.value = res.data
  })
}

const loginRequest = ref<LoginRequest>({
  password: ""
})
const accessToken = useLocalStorage(ACCESS_TOKEN_NAME, "")
const router = useRouter()

function login() {
  loginRequest.value.captchaId = captcha.value?.id
  doLogin(loginRequest.value).then((res) => {
    accessToken.value = res.data
    router.push({ path: "/home" })
  })
}
</script>

<style scoped lang="scss">
@import "index.scss";
</style>
